package com.example.project.api.controller;

import cn.hutool.core.date.DateUtil;
import com.example.project.api.dto.GiftDTO;
import com.example.project.api.model.TbUser;
import com.example.project.api.model.TbWin;
import com.example.project.api.service.TbBoxService;
import com.example.project.api.service.TbUserService;
import com.example.project.api.service.TbWinService;
import com.example.project.common.tools.AppException;
import com.example.project.common.tools.R;
import com.example.project.common.tools.ResponseEnum;
import com.example.project.common.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * (box)表控制层
 *
 * @author ZhangHongRui
 */
@Slf4j
@RestController
@RequestMapping("/box")
public class TbBoxController {

    @Autowired
    private TbBoxService tbBoxService;
    @Autowired
    private TbUserService tbUserService;
    @Autowired
    private TbWinService tbWinService;

    /**
     * 获取盲盒
     *
     * @return
     */
    @GetMapping("/getBox")
    public R getBox(HttpServletRequest request) {
        GiftDTO giftDTO;
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        try {
            // 获取IP进行验证
            String ip = Utils.getIpAddr(request);
            TbUser tbUser = tbUserService.getUserByIp(ip);
            if (tbUser.getUserNum() == 0) {
                throw new AppException(ResponseEnum.INADEQUATE_IN_NUMBER);
            }
            // 抽取盲盒
            giftDTO = tbBoxService.getBox(ip);
            if (ObjectUtils.isEmpty(giftDTO)) {
                throw new AppException(ResponseEnum.BOX_OVER);
            }
            tbUser.setUserNum(tbUser.getUserNum() - 1);
            tbUserService.updateById(tbUser);
            log.info("ip:{} 抽到了价值{}元的{}盲盒,当前时间:{}", ip, giftDTO.getPrice(), giftDTO.getName(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } finally {
            lock.unlock();
        }
        return new R(ResponseEnum.SUCCESS, giftDTO);
    }

}
